<template>
  <view class="dynamics-wrapper">
    <!-- 动态列表 -->
    <view class="dynamics-list">
      <!-- 空数据状态 -->
      <view v-if="dynamicsList.length === 0 && !loading" class="empty-state">
        <view class="empty-icon">📝</view>
        <text class="empty-text">暂无动态内容</text>
        <text class="empty-subtext">快来发布第一条动态吧！</text>
      </view>

      <!-- 动态列表内容 -->
      <view
        v-for="(item, index) in filteredDynamics"
        :key="item._id || index"
        class="dynamic-item"
        @click="goToDetail(item)"
      >
        <!-- 用户信息 -->
        <view class="user-info">
          <image
            :src="item.author?.avatar || '/static/images/img/wxm.jpg'"
            class="user-avatar"
            mode="aspectFill"
          ></image>
          <view class="user-details">
            <text class="username">{{ getDisplayName(item) }}</text>
            <text class="post-time">{{ formatTime(item.createdata) }}</text>
          </view>
          <view class="more-btn">
            <text class="more-icon">⋯</text>
          </view>
        </view>

        <!-- 动态内容 -->
        <view class="dynamic-content">
          <text class="content-text">{{ item.context }}</text>
        </view>

        <!-- 附件区域 -->
        <view
          v-if="item.img && item.img.length > 0"
          class="attachments-container"
        >
          <view class="attachments-grid">
            <view
              v-for="(imageUrl, attIndex) in item.img"
              :key="attIndex"
              class="attachment-item"
              @click.stop="previewAttachment(imageUrl, item.img)"
            >
              <!-- 图片附件 -->
              <image
                :src="imageUrl"
                class="attachment-image"
                mode="aspectFill"
                :alt="`图片${attIndex + 1}`"
                @click.stop="previewAttachment(imageUrl, item.img)"
              />
            </view>
          </view>
        </view>

        <!-- 分类标签 -->
        <view v-if="item.topic && item.topic.length > 0" class="category-tag">
          <Tag :tags="item.topic" :defaultTag="item.topic[0]" />
        </view>

        <!-- 互动统计 -->
        <InteractionStats
          :views="item.views || 0"
          :commentsCount="item.comments || 0"
          :likeCount="item.likes ? item.likes.length : 0"
          :isLiked="likedItems.has(item._id)"
          @like-click="handleLike(item)"
        />
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="load-more-container">
      <view v-if="loading" class="loading-item">
        <view class="loading-icon">⏳</view>
        <text class="loading-text">加载中...</text>
      </view>
      <view v-else-if="noMore" class="no-more-item">
        <text class="no-more-text">没有更多了</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed } from "vue";
import Tag from "./tag.vue";
import InteractionStats from "./interaction.vue";

// 声明uni全局对象
declare const uni: any;

// 定义类型接口 - 适配后端数据结构
interface DynamicItem {
  _id: string;
  context: string;
  img: string[];
  topic: string[];
  anonymity: boolean;
  top_time: string;
  comments: number;
  likes: string[];
  views: number;
  tag: string[];
  author: {
    _id: string;
    name: string;
    avatar?: string;
  };
  createdata: string;
}

// 定义props
interface Props {
  dynamicsList: DynamicItem[];
  loading: boolean;
  noMore: boolean;
  likedItems: Set<string | number>;
}

const props = defineProps<Props>();

// 定义emits
const emit = defineEmits<{
  likeClick: [item: DynamicItem];
}>();

// 计算属性
const filteredDynamics = computed(() => {
  // console.log('dynamics_list 组件接收到的数据:', props.dynamicsList);
  // console.log('dynamics_list 数据长度:', props.dynamicsList.length);
  return props.dynamicsList;
});

// 格式化时间
const formatTime = (timeStr: string) => {
  try {
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 30) return `${days}天前`;
    
    return date.toLocaleDateString();
  } catch (error) {
    return '未知时间';
  }
};

// 获取显示的用户名
const getDisplayName = (item: DynamicItem) => {
  // 如果 anonymity 为 true，显示匿名用户
  if (item.anonymity === true) {
    return '匿名用户';
  }
  
  // 如果 anonymity 为 false 或未设置，显示真实用户名
  return item.author?.name || '未知用户';
};

// 方法
const goToDetail = (item: DynamicItem) => {
  console.log("查看动态详情:", item);
  // 跳转到动态详情页面，携带动态数据
  uni.navigateTo({
    url: `/pages/main/mainpages/dynamic_details?dynamicId=${item._id}`,
    success: () => {
      console.log('跳转成功');
    },
    fail: (error: any) => {
      console.error('跳转失败:', error);
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      });
    }
  });
};

const handleLike = (item: DynamicItem) => {
  emit("likeClick", item);
};

// 附件相关方法
const isImage = (url: string): boolean => {
  const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"];
  const lowerUrl = url.toLowerCase();
  return imageExtensions.some((ext) => lowerUrl.includes(ext));
};

const isVideo = (url: string): boolean => {
  const videoExtensions = [
    ".mp4",
    ".avi",
    ".mov",
    ".wmv",
    ".flv",
    ".webm",
    ".mkv",
  ];
  const lowerUrl = url.toLowerCase();
  return videoExtensions.some((ext) => lowerUrl.includes(ext));
};

const previewAttachment = (
  imageUrl: string,
  images: string[]
) => {
  console.log('预览图片:', imageUrl);
  if (isImage(imageUrl)) {
    // 预览图片
    uni.previewImage({
      current: imageUrl,
      urls: images.filter((url) => isImage(url)),
      success: () => {
        console.log('图片预览成功');
      },
      fail: (error: any) => {
        console.error('图片预览失败:', error);
        uni.showToast({
          title: '图片预览失败',
          icon: 'none'
        });
      }
    });
  } else {
    console.log('不是图片文件:', imageUrl);
  }
};
</script>

<style lang="scss" scoped>
/* 动态列表 */
.dynamics-list {
  margin-top: 20px;
  margin-bottom: 35px;
  background-color: #fff;
}

.dynamic-item {
  background-color: #fff;
  margin: 5px 0;
  padding: 25rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  border: 1rpx solid rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.08);
  }

  &:first-child {
    margin-top: 5rpx;
  }
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.user-avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  margin-right: 15rpx;
  background-color: #f0f0f0;
  flex-shrink: 0;
}

.user-details {
  flex: 1;
}

.username {
  display: block;
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 4rpx;
}

.post-time {
  font-size: 22rpx;
  color: #999;
}

.more-btn {
  padding: 8rpx;
}

.more-icon {
  font-size: 28rpx;
  color: #ccc;
}

/* 动态内容 */
.dynamic-content {
  margin-bottom: 18rpx;
}

.content-text {
  font-size: 28rpx;
  line-height: 1.5;
  color: #333;
}

/* 分类标签 */
.category-tag {
  margin-bottom: 20rpx;
}

/* 附件区域样式 */
.attachments-container {
  margin-bottom: 20rpx;
}

.attachments-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.attachment-item {
  position: relative;
  cursor: pointer;
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.95);
  }
}

.attachment-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  object-fit: cover;
  border: 1rpx solid #f0f0f0;
}

.video-container {
  position: relative;
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  overflow: hidden;
  border: 1rpx solid #f0f0f0;
}

.attachment-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
}

.file-container {
  width: 120rpx;
  height: 120rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  border: 1rpx solid #f0f0f0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.file-icon {
  font-size: 32rpx;
  color: #666;
}

.file-name {
  font-size: 20rpx;
  color: #666;
  text-align: center;
  line-height: 1.2;
  max-width: 100rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 空数据状态 */
.empty-state {
  text-align: center;
  background-color: #fff;
  border-radius: 16rpx;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  opacity: 0.6;
}

.empty-text {
  display: block;
  font-size: 32rpx;
  color: #666;
  margin-bottom: 10rpx;
  font-weight: 500;
}

.empty-subtext {
  display: block;
  font-size: 26rpx;
  color: #999;
}

/* 加载状态 */
.load-more-container {
  padding: 30rpx 0;
  text-align: center;
}

.loading-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15rpx;
}

.loading-icon {
  font-size: 32rpx;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.no-more-item {
  padding: 20rpx 0;
}

.no-more-text {
  font-size: 26rpx;
  color: #ccc;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .dynamic-item {
    margin: 0 12rpx 12rpx;
    padding: 20rpx;
    border-radius: 10rpx;
  }

  .user-avatar {
    width: 60rpx;
    height: 60rpx;
  }

  .username {
    font-size: 26rpx;
  }

  .post-time {
    font-size: 20rpx;
  }

  .content-text {
    font-size: 26rpx;
  }
}
</style>